/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package snail.Servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import snail.data.ArticleDAO;
import snail.data.UserDAO;
import snail.hibernate.util.HibernateUtil;
import snail.model.Article;
import snail.model.User;

/**
 *
 * @author viktor
 */
public class UnWatchServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            int articleId = Integer.parseInt(request.getParameter("id"));
            User sessUser = (User) request.getSession().getAttribute("user");

            if (sessUser == null) {
                out.println("error.Logga in please");
            } else {
                Session session = HibernateUtil.getSessionFactory().getCurrentSession();
                session.beginTransaction();

                User user = new UserDAO().getById(sessUser.getUserId());
                Article article = new ArticleDAO().getById(articleId);
                article.getWatchingUsers().remove(user);
                session.update(article);
                session.getTransaction().commit();
                
                out.printf("Bevakning av \"%s\" borttagen", article.getTitle());
            }

        } catch (NumberFormatException ex) {
            out.println("error.Invalid argument.");
        } catch (Exception ex) {
            out.println("error.Nåt gick fel: " + ex.getMessage());
        } finally {
            out.close();
        }
    }
}
